<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="套餐名称" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入套餐名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="套餐状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:package:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:package:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:package:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:package:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="套餐ID" align="center" prop="packageId" width="80" />
      <el-table-column label="套餐名称" align="center" prop="packageName" :show-overflow-tooltip="true" />
      <el-table-column label="最大用户数" align="center" prop="maxUserCount" width="100" />
      <el-table-column label="最大部门数" align="center" prop="maxDeptCount" width="100" />
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:package:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:package:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改租户套餐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="套餐名称" prop="packageName">
              <el-input v-model="form.packageName" placeholder="请输入套餐名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大用户数" prop="maxUserCount">
              <el-input-number 
                v-model="form.maxUserCount" 
                :min="1" 
                :max="100000" 
                placeholder="请输入最大用户数" 
                style="width: 100%" 
                controls-position="right"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大部门数" prop="maxDeptCount">
              <el-input-number 
                v-model="form.maxDeptCount" 
                :min="1" 
                :max="10000" 
                placeholder="请输入最大部门数" 
                style="width: 100%" 
                controls-position="right"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="菜单权限" prop="menuIds">
          <el-tree
            ref="menuTree"
            :data="menuOptions"
            :props="{ label: 'label', children: 'children' }"
            node-key="id"
            empty-text="加载中，请稍后"
            show-checkbox
            check-strictly
            :default-checked-keys="Array.isArray(form.menuIds) ? form.menuIds : []"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPackage, getPackage, delPackage, addPackage, updatePackage } from "@/api/system/package";
import { treeselect as menuTreeselect } from "@/api/system/menu";

export default {
  name: "Package",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 租户套餐表格数据
      packageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 菜单树选项
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        packageName: [
          { required: true, message: "套餐名称不能为空", trigger: "blur" }
        ],
        maxUserCount: [
          { required: true, message: "最大用户数不能为空", trigger: "blur" }
        ],
        maxDeptCount: [
          { required: true, message: "最大部门数不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      },
      menuIds: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询租户套餐列表 */
    getList() {
      this.loading = true;
      listPackage(this.queryParams).then(response => {
        this.packageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询菜单下拉树结构 */
    getMenuTreeselect() {
      menuTreeselect().then(response => {
        this.menuOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        packageId: undefined,
        packageName: undefined,
        maxUserCount: 10,
        maxDeptCount: 5,
        menuIds: [],
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
      if (this.$refs.menuTree) {
        this.$refs.menuTree.setCheckedKeys([]);
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.open = true;
      this.title = "添加租户套餐";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getMenuTreeselect();
      const packageId = row.packageId || this.ids;
      getPackage(packageId).then(response => {
        this.form = response.data;
        this.menuIds = response.data.menuIds;
        // 确保 menuIds 是数组格式
        if (typeof this.form.menuIds === 'string') {
          this.form.menuIds = this.form.menuIds ? this.form.menuIds.split(',').map(Number) : [];
        } else if (!Array.isArray(this.form.menuIds)) {
          this.form.menuIds = [];
        }
        
        console.log('修改数据 - menuIds:', this.form.menuIds, '类型:', typeof this.form.menuIds);
        
        this.open = true;
        this.title = "修改租户套餐";
        this.$nextTick(() => {
          if (this.$refs.menuTree) {
            // 设置选中的节点
            this.$refs.menuTree.setCheckedKeys(this.form.menuIds);
            
            // 对于已经保存的数据，如果只保存了叶子节点而没有保存父节点，
            // 我们需要确保父节点也被选中
            this.ensureParentNodesSelected();
          }
        });
      }).catch(error => {
        console.error('获取套餐详情失败:', error);
      });
    },
    
    /** 确保父节点被选中 */
    ensureParentNodesSelected() {
      const tree = this.$refs.menuTree;
      if (!tree) return;
      
      // 获取当前选中的节点
      const checkedKeys = tree.getCheckedKeys();
      
      // 查找所有选中节点的父节点
      const allKeysWithParents = this.getAllParentKeys(checkedKeys, this.menuOptions);
      
      console.log('回显时 - 原始选中节点:', checkedKeys);
      console.log('回显时 - 包含父节点的所有节点:', allKeysWithParents);
      
      // 重新设置选中状态，确保父节点也被选中
      if (allKeysWithParents.length > 0) {
        tree.setCheckedKeys(allKeysWithParents);
      }
    },
    
    /** 递归查找所有父节点 */
    getAllParentKeys(checkedKeys, treeData) {
      const result = [...checkedKeys];
      
      // 递归查找每个选中节点的父节点
      const findParents = (nodeId, nodes, path = []) => {
        for (const node of nodes) {
          if (node.id === nodeId) {
            return [...path];
          }
          
          if (node.children && node.children.length > 0) {
            const found = findParents(nodeId, node.children, [...path, node.id]);
            if (found) {
              // 将路径上的所有父节点添加到结果中
              found.forEach(parentId => {
                if (!result.includes(parentId)) {
                  result.push(parentId);
                }
              });
              return found;
            }
          }
        }
        return null;
      };
      
      // 对每个选中的节点查找父节点
      checkedKeys.forEach(key => {
        findParents(key, treeData);
      });
      
      return result;
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取所有选中的节点（包括父节点）
          const tree = this.$refs.menuTree;
          // 方法1：使用递归获取所有选中的节点及其父节点
          const allCheckedKeys = this.getAllCheckedKeysWithParents(tree);
          this.form.menuIds = allCheckedKeys.join(',');
          // 检查是否包含了必要的目录节点
          this.checkMenuStructure(allCheckedKeys);
          
          if (this.form.packageId != null) {
            // 检查菜单权限是否发生变化
            if(this.menuIds != this.form.menuIds){
              // 菜单权限发生变化，弹出确认对话框
              this.$confirm('修改菜单权限将会重新初始化绑定该套餐的租户角色菜单数据，是否继续？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // 用户点击确定后执行更新
                updatePackage(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }).catch(() => {
                  // 更新失败的处理（可选）
                  this.$modal.msgError("修改失败");
                });
              }).catch(() => {
                // 用户点击取消，不做任何操作
                this.$message({
                  type: 'info',
                  message: '已取消修改'
                });
              });
            } else {
              // 套餐未变化，直接更新
              updatePackage(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          } else {
            addPackage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('新增失败:', error);
            });
          }
        }
      });
    },
    
    /** 获取所有选中的节点及其父节点 */
    getAllCheckedKeysWithParents(tree) {
      // 获取当前选中的节点
      const checkedKeys = tree.getCheckedKeys();
      console.log("checkedKeys", checkedKeys);
      
      // 获取半选中的节点（当子节点被选中时，父节点是半选状态）
      const halfCheckedKeys = tree.getHalfCheckedKeys();
      console.log("halfCheckedKeys", halfCheckedKeys);
      
      // 合并选中的节点和半选中的节点
      const allKeys = [...new Set([...checkedKeys, ...halfCheckedKeys])];
      
      // 递归查找这些节点的所有父节点
      const allKeysWithParents = this.getAllParentKeys(allKeys, this.menuOptions);
      
      console.log("最终提交的节点:", allKeysWithParents);
      
      return allKeysWithParents;
    },
    
    /** 检查菜单结构 */
    checkMenuStructure(menuIds) {
      // 检查是否包含了必要的目录节点
      const missingParents = [];
      
      // 创建一个函数来查找节点的父节点
      const findParent = (nodeId, tree) => {
        for (const node of tree) {
          if (node.id === nodeId) {
            return null; // 找到了节点，不需要父节点
          }
          if (node.children && node.children.length > 0) {
            const childIds = this.getAllChildIds(node);
            if (childIds.includes(nodeId)) {
              // 检查父节点是否在menuIds中
              if (!menuIds.includes(node.id)) {
                missingParents.push(node.id);
              }
              // 继续向上查找
              return node.id;
            }
          }
        }
        return null;
      };
      
      // 遍历所有选中的节点，检查其父节点
      menuIds.forEach(id => {
        findParent(id, this.menuOptions);
      });
      
      if (missingParents.length > 0) {
        console.warn("以下目录节点可能缺失:", missingParents);
      }
    },
    
    /** 获取节点的所有子节点ID */
    getAllChildIds(node) {
      let ids = [];
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          ids.push(child.id);
          ids = ids.concat(this.getAllChildIds(child));
        });
      }
      return ids;
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const packageIds = row.packageId || this.ids;
      this.$modal.confirm('是否确认删除租户套餐编号为"' + packageIds + '"的数据项？').then(function() {
        return delPackage(packageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/package/export', {
        ...this.queryParams
      }, `package_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.el-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
}
</style>